package com.hh.hot100;

/**
 * @Author hanghao
 * @Date 2023/6/27 13:33
 * @Version 1.0
 * easy
 * 链表相交
 */

public class No160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;
        int lenA = 0, lenB = 0;
        while (curA != null) {
            curA = curA.next;
            lenA++;
        }
        while (curB != null) {
            curB = curB.next;
            lenB++;
        }
        //这一步很容易忘的  假如没有把当前指针移动的操作，后面根本走不了
        curA = headA;
        curB = headB;
        // 让curA为最长链表的头，lenA为其长度
        if (lenB > lenA) {
            int tempLen = lenA;
            lenA = lenB;
            lenB = tempLen;
            ListNode tempNode = curA;
            curA = curB;
            curB = tempNode;
        }
        int len = lenA - lenB;
        while(len > 0) {
            curA = curA.next;
            len--;
        }
        while(curA != null) {
            if(curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}
